//
//  STStatusPictureView.swift
//  STVVeibo
//
//  Created by leergou on 16/7/25.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit

let pictureViewCellMargin: CGFloat = 5
let cellWidth: CGFloat = 80

private let STStatusPictureCellID = "STStatusPictureCellID"

class STStatusPictureView: UICollectionView {
    
    // 定义模型属性,给内部空间赋值
    var pictureInfo: [STPictureInfo]?{
        
        didSet{
            // countLabel 赋值
            countLabel.text = "\(pictureInfo?.count ?? 0)"
            // 获取当前配图的size
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            // 更新当前配图约束
            // 第一次写成了 make,导致 cell 重用的时候,提示约束冲突
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新 UI - 记住刷新 否则数据拿到了但是界面不显示
            reloadData()
        }
    }
    
    func getPictureViewSize(count: Int) -> CGSize{
        // 计算行数 和 列数
        let col = count == 4 ? 2 : (count >= 3 ? 3 : count)
        let row = count == 4 ? 2 : ((count - 1) / 3 + 1)
        
        // 计算 size 
        let wid = CGFloat(col) * cellWidth + CGFloat(col - 1) * pictureViewCellMargin
        let hei = CGFloat(row) * cellWidth + CGFloat(row - 1) * pictureViewCellMargin
        return CGSize(width: wid, height: hei)
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // setupUI
    private func setupUI(){
        self.backgroundColor = UIColor.clearColor()
        // 获取布局对象
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        layout.minimumInteritemSpacing = pictureViewCellMargin
        layout.minimumLineSpacing = pictureViewCellMargin
        
        // 注册 cell
        registerClass(STStatusPictureViewCell.self, forCellWithReuseIdentifier: STStatusPictureCellID)
        // 设置数据源代理
        dataSource = self
        delegate = self
        
        // 添加 计数label
        addSubview(countLabel)
        // 约束
        countLabel.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: 20, height: 20))
            make.center.equalTo(self)
        }
    }
    
    //MARK: lazy
    private lazy var countLabel: UILabel = UILabel(font: 35, textColor: UIColor.redColor(), maxWidth: 0)
}

////MARK: collectionView dataSource
extension STStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfo?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(STStatusPictureCellID, forIndexPath: indexPath) as! STStatusPictureViewCell
        
        cell.pic_urls = pictureInfo?[indexPath.item]
        
        return cell
    }
    
    // 实现点击大图
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        // 当前选中图片
        photoBrowser.currentImageIndex = indexPath.item
        // 总图的个数
        photoBrowser.imageCount = pictureInfo!.count
        // 父控件
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
    
}

//MARK: photoBrowser delegate
extension STStatusPictureView:SDPhotoBrowserDelegate{
    
    // 小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! STStatusPictureViewCell
        
        return cell.imgView.image
    }
    
    // 高清图
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        var urlStr = pictureInfo![index].thumbnail_pic!
        urlStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
    }
    
}



//MARK: 自定义 cell
class STStatusPictureViewCell: UICollectionViewCell {
    
    // 定义一个模型属性 ,供外界赋值
    var pic_urls: STPictureInfo?{
        
        didSet{
            // 设置 imge
            imgView.st_setImage(pic_urls?.thumbnail_pic, placeholderImgName: "weibo_placeholder")
            
            // 判断是否 为nil
            if let thPic = pic_urls?.thumbnail_pic where thPic.hasSuffix(".gif") {
                
                gifLogo.hidden = false
            } else {
                gifLogo.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // setupUI
    private func setupUI(){
//        backgroundColor = RGB(237, green: 237, blue: 237)
        // 添加子控件
        contentView.addSubview(imgView)
        contentView.addSubview(gifLogo)
        // 添加约束
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifLogo.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
        
    }
    
    //MARK: lazy
    private lazy var imgView: UIImageView = {
        
        let img = UIImageView(imgName: "weibo_placeholder")
        img.contentMode = .ScaleAspectFill
        img.layer.masksToBounds = true
        return img
    }()
    
    private lazy var gifLogo: UIImageView = {
       
        let img = UIImageView(imgName: "timeline_image_gif")
       return img
    }()
    
}






